<template>
  <div style="background-color: #fff">
    <PageHeader @back="goBackPage" subTitle="返回"> </PageHeader>
    <div class="body">
      <div class="headerBox" style="height: 104px; border: 1px solid #e8e8e8">
        <div style="display: flex">
          <div>
            <img :src="require('@/assets/icons/importImg.png')" style="width: 56px; height: 56px" alt="" />
          </div>
          <div class="textBox">
            <div style="font-size: 18px; font-weight: 500; color: #3c3d43; margin-left: 24px">{{ actionForm.TaskName }}</div>
            <div style="display: flex">
              <div class="contentName">
                派单月份：<span style="color: #55565d">{{
                  actionForm.selectDate
                    ? moment(actionForm.selectDate).format("YYYY") + "年" + moment(actionForm.selectDate).format("MM") + "月"
                    : "--"
                }}</span>
              </div>
              <div class="contentName">
                派单模式：<span style="color: #55565d">{{ actionForm.tableName }}</span>
              </div>
              <div
                v-if="actionForm.companyList.length > 0"
                class="contentName"
                style="width: 350px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
              >
                派单对象：<span style="color: #55565d" v-for="(item, index) in actionForm.companyList" :key="index">{{
                  item.label + "    "
                }}</span>
              </div>
              <div
                v-if="actionForm.selectCompanyId.length > 0"
                class="contentName"
                style="width: 350px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap"
              >
                派单对象：<span v-for="(item, index) in actionForm.selectCompanyId" :key="index">{{ item.label + "    " }}</span>
              </div>
            </div>
          </div>
        </div>
        <div style="margin-top: 12px">
          <a-button @click="showEdit">编辑</a-button>
        </div>
      </div>
      <a-modal title="编辑" :width="600" :visible="editVisible" @cancel="editVisible = false" @ok="editOk">
        <a-form class="form" :form="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-row>
            <a-form-item class="form-item" label="派单任务名称">
              <a-input v-model="TaskName" placeholder="请输入" style="width: 300px" />
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item label="选择模式">
              <SelectWithInputAdd v-model="tableName" editable allowClear dictCode="1204" placeholder="请选择模式" style="width: 300px" />
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item class="form-item" label="选择月份">
              <a-month-picker v-model="selectDate" format="YYYY-MM" style="width: 300px" placeholder="请选择" />
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item class="form-item" label="选择派单对象">
              <a-radio-group name="radioGroup" v-model="comtype" @change="onRadioChange">
                <a-radio :value="1"> 固定用工单位 </a-radio>
                <a-radio :value="2"> 固定业务员 </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item class="form-item" label="派单单位/业务员">
              <a-tree-select
                v-if="comtype === 1"
                v-model="companyList"
                :tree-data="companyTreeWithUuid"
                :filterTreeNode="false"
                :replaceFields="replaceFields2"
                labelInValue
                showSearch
                treeNodeFilterProp="title"
                placeholder="请选择用工单位"
                treeCheckable
                style="width: 300px"
              />
              <a-select
                labelInValue
                mode="multiple"
                option-filter-prop="children"
                :filter-option="filterOption"
                v-if="comtype === 2"
                v-model="selectCompanyId"
                placeholder="请选择业务员"
                style="width: 300px"
              >
                <a-select-option v-for="i in dataSource" :key="i.id">
                  {{ i.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-row>
        </a-form>
      </a-modal>
      <a-modal title="发现错误数据" :visible="erroInfo" @cancel="erroInfo = false">
        <template slot="footer">
          <a-button key="submit" @click="erroInfo = false"> 取消 </a-button>
          <a-button key="submit" type="primary" @click="erroNext"> 继续 </a-button>
        </template>
        <div class="rowdalog2">
          <img style="width: 30px; height: 30px; margin-right: 10px" src="@/assets/icons/ask.png" />
          <!-- -->
          <div style="margin-top: 4px; color: #3c3d43; font-size: 16px; font-weight: 400">将只导入正确数据，忽略错误数据，是否继续？</div>
        </div>
      </a-modal>
      <a-alert v-if="numberOfErr === 0" style="margin-top: 24px" type="success" show-icon>
        <div slot="description" style="display: flex; justify-content: space-between">
          <div>
            {{ "导入社保派单“" + $route.query.fileName + "”共" + datalist.length + "人，无异常数据" }}
          </div>
        </div>
      </a-alert>
      <a-alert v-if="numberOfErr > 0" style="margin-top: 24px" type="error" show-icon>
        <div slot="description" style="display: flex; justify-content: space-between">
          <div>
            {{ "导入社保派单“" + $route.query.fileName + "”共" + datalist.length + "人，有" + numberOfErr + "条数据异常，请尽快处理" }}
          </div>
          <div style="color: #ff7085; cursor: pointer" @click="importErrData">导出错误数据</div>
        </div>
      </a-alert>
      <div style="margin-top: 24px">
        <a-table :columns="columns" :scroll="{ x: 1200 }" :data-source="datalist" :pagination="false" row-key="id">
          <div slot="姓名" style="position: relative" slot-scope="text, record">
            <div v-if="record.nameWrongs && !record.keep === true" class="errImg" style="position: absolute; top: -18px; left: -15px" />
            <div v-if="record.keep === true && record.nameWrongs" class="ignoreImg" style="position: absolute; top: -18px; left: -15px" />
            <a-popover title="数据错误">
              <template slot="content">
                <span>{{ record.nameWrongs }}</span>
              </template>
              <span style="margin-bottom: 0; cursor: pointer" v-if="record.nameWrongs">
                {{ text ? text : "--" }}
              </span>
            </a-popover>
            <span v-if="!record.nameWrongs"> {{ text }}</span>
          </div>
          <div slot="身份证号" style="position: relative" slot-scope="text, record">
            <div v-if="record.idCardWrongs && !record.keep === true" class="errImg" style="position: absolute; top: -18px; left: -15px" />
            <div v-if="record.keep === true && record.idCardWrongs" class="ignoreImg" style="position: absolute; top: -18px; left: -15px" />
            <a-popover title="数据错误">
              <template slot="content">
                <span>{{ record.idCardWrongs }}</span>
              </template>
              <span style="margin-bottom: 0; cursor: pointer" v-if="record.idCardWrongs">
                {{ text ? text : "--" }}
              </span>
            </a-popover>
            <span v-if="!record.idCardWrongs"> {{ text }}</span>
          </div>
          <div slot="action" slot-scope="text, record, index">
            <a-button
              size="small"
              type="link"
              @click="keepErrItem(record)"
              v-if="record.nameWrongs || record.idCardWrongs"
              :disabled="record.keep === true"
              >保留</a-button
            >
            <a-button size="small" type="link" style="color: #ff7085" @click="deleteItem(index)">删除</a-button>
          </div>
        </a-table>
      </div>
      <div style="margin-top: 24px; display: flex; margin-left: 45%">
        <a-button @click="goBackPage">重新上传</a-button>
        <a-button @click="saveExcel" type="primary" style="margin-left: 24px">下一步</a-button>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { saveExcel } from "./api";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
import SelectWithInputAdd from "xqjr-plugin-form/components/XqSelectWithInputAdd.vue";
const mixin = new ExportMixin();
export default {
  mixins: [mixin],
  components: { SelectWithInputAdd },
  data() {
    return {
      replaceFields2: {
        children: "companyList",
        title: "name",
        key: "uuid",
        value: "uuid"
      },
      companyList: [],
      labelCol: { span: 7 },
      wrapperCol: { span: 14 },
      form: this.$form.createForm(this, { name: "coordinated" }),
      moment,
      columns: [],
      list: [],
      selectDate: undefined,
      tableName: undefined,
      TaskName: undefined,
      datalist: [],
      dataList2: [],
      dataSource: [],
      actionForm: {},
      selectCompanyId: [],
      headDate: [],
      comtype: 1,
      editVisible: false,
      erroInfo: false
    };
  },
  computed: {
    companyTreeWithUuid() {
      return this.$store.state.site.companyTreeWithUuid;
    },
    companyUuidDict() {
      return this.$store.state.site.companyUuidDict;
    }
  },
  watch: {
    TaskName(e) {
      sessionStorage.setItem("TaskName", e);
    },
    selectDate(e) {
      sessionStorage.setItem("selectDate", e);
    },
    companyList(e) {
      sessionStorage.setItem("companyList", JSON.stringify(this.companyList));
    },
    selectCompanyId(e) {
      sessionStorage.setItem("selectCompanyId", JSON.stringify(this.selectCompanyId));
    },
    companyTreeWithUuid: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.companyList = JSON.parse(sessionStorage.getItem("companyList"));
        }
      },
      immediate: true
    }
  },
  created() {
    this.getUserRolesList();
    // 路由数据
    this.datalist = JSON.parse(this.$route.query.list);
    this.numberOfErr = 0;
    this.erroInfo = false;
    this.datalist.forEach((item, index) => {
      if (item.nameWrongs || item.idCardWrongs) {
        this.numberOfErr = this.numberOfErr + 1;
      }
    });
    this.actionForm = JSON.parse(this.$route.query.form);
    this.actionForm.companyList = JSON.parse(this.actionForm.companyList);
    this.actionForm.selectCompanyId = JSON.parse(this.actionForm.selectCompanyId);
    this.tableName = this.actionForm.tableName;
    var arr = [];

    arr = JSON.parse(this.$route.query.head);
    // 动态表头，区分每列宽度，定位等
    arr.forEach((item, index) => {
      this.columns.push({
        title: `${item}`,
        dataIndex: `${item}`,
        align: "center",
        width: item === "身份证号" ? 220 : 150,
        scopedSlots: { customRender: `${item}` },
        ellipsis: true,
        fixed: item === "身份证号" || item === "姓名" ? "left" : null
      });
    });
    this.columns.push({
      title: `操作`,
      dataIndex: `action`,
      align: "left",
      width: 150,
      scopedSlots: { customRender: `action` },
      ellipsis: true,
      fixed: "right"
    });
  },
  methods: {
    async getUserRolesList() {
      const { data } = await this.$request({ url: `/hr/api/v1/users/list` });
      this.dataSource = data;
    },
    onRadioChange(e) {
      this.companyList = [];
      this.selectCompanyId = [];
      sessionStorage.setItem("comtype", this.comtype);
    },
    editOk() {
      if (this.companyList.length > 0 || this.selectCompanyId.length > 0) {
        this.editVisible = false;
        this.actionForm.TaskName = this.TaskName;
        this.actionForm.tableName = this.tableName;
        this.actionForm.selectDate = this.selectDate;
        this.actionForm.comtype = this.comtype;
        this.actionForm.companyList = JSON.parse(JSON.stringify(this.companyList));
        this.actionForm.selectCompanyId = JSON.parse(JSON.stringify(this.selectCompanyId));
      } else {
        this.$message.error("派单单位/业务员必选");
      }
    },
    showEdit() {
      this.editVisible = true;
      this.TaskName = sessionStorage.getItem("TaskName") ? sessionStorage.getItem("TaskName") : undefined;
      this.tableName = sessionStorage.getItem("tableName") ? sessionStorage.getItem("tableName") : undefined;
      this.selectDate = sessionStorage.getItem("selectDate") ? sessionStorage.getItem("selectDate") : undefined;
      this.comtype = sessionStorage.getItem("comtype") ? parseInt(sessionStorage.getItem("comtype")) : 1;
      this.companyList = sessionStorage.getItem("companyList") ? JSON.parse(sessionStorage.getItem("companyList")) : [];
      this.selectCompanyId = sessionStorage.getItem("selectCompanyId") ? JSON.parse(sessionStorage.getItem("selectCompanyId")) : [];
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    goBackPage() {
      this.$router.push({
        path: "/admin/shebaoUpload",
        query: {
          pageState: 2
        }
      });
    },
    // 导出错误数据
    importErrData() {
      var arr = [];
      this.datalist.forEach((item, index) => {
        if (item.nameWrongs || item.idCardWrongs) {
          arr.push(item);
        }
      });
      this.exportData = {
        head: JSON.parse(this.$route.query.head),
        headDate: arr
      };
      this.url = `/hr/api/v1/missionCenters/exportWrongsData`;
      this.excelName = "错误数据导出详情.xlsx";
      this.postDownload();
    },
    // 点击列表删除
    deleteItem(index) {
      this.datalist.splice(index, 1);
      this.datalist = JSON.parse(JSON.stringify(this.datalist));
      this.numberOfErr = 0;
      this.datalist.forEach((item, index) => {
        if (item.nameWrongs || item.idCardWrongs) {
          this.numberOfErr = this.numberOfErr + 1;
        }
      });
    },
    // 点击列表保留
    keepErrItem(e) {
      e.keep = true;
      this.datalist = JSON.parse(JSON.stringify(this.datalist));
    },
    // 点击下一步
    saveExcel() {
      this.erroInfo = false;
      if (this.numberOfErr !== 0) {
        this.erroInfo = true;
      } else {
        this.saveExcelNext();
      }
    },
    erroNext() {
      this.erroInfo = false;
      this.saveExcelNext();
    },
    saveExcelNext() {
      var arr = [];
      if (this.actionForm.companyList.length > 0) {
        this.actionForm.companyList.forEach((item, index) => {
          arr.push(this.companyUuidDict[item.value]);
        });
      }
      if (this.actionForm.selectCompanyId.length > 0) {
        this.actionForm.selectCompanyId.forEach((item, index) => {
          arr.push(item.key);
        });
      }

      var noErrDataList = [];
      this.datalist.forEach((item, index) => {
        if ((!item.idCardWrongs && !item.nameWrongs) || item.keep === true) {
          noErrDataList.push(item);
        }
      });
      arr = arr.join(",");
      saveExcel({
        missionName: this.actionForm.TaskName,
        month: moment(this.actionForm.selectDate).format("MM"),
        year: moment(this.actionForm.selectDate).format("YYYY"),
        state: 0,
        subjectType: this.actionForm.comtype,
        missionMode: this.actionForm.tableName,
        subjectId: arr,
        head: JSON.parse(this.$route.query.head),
        headDate: noErrDataList,
        fileUrl: this.$route.query.urlList[0],
        fileName: this.$route.query.fileName
      }).then((res) => {
        this.$router.push({ path: "/admin/shebao-add-list-third", query: { num: noErrDataList.length } });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.errImg {
  width: 0;
  height: 0;
  border-top: 10px solid red;
  border-right: 10px solid transparent;
}
.ignoreImg {
  width: 0;
  height: 0;
  border-top: 10px solid #959595;
  border-right: 10px solid transparent;
}
.body {
  padding: 24px;
}
.textBox {
  display: flex;
  flex-direction: column;
}
.headerBox {
  width: 100%;
  display: flex;
  justify-content: space-between;
  background: #ffffff;
  border-radius: 4px;
  padding: 24px;
}
.contentName {
  margin-top: 12px;
  font-size: 14px;
  font-weight: 400;
  color: #767885;
  margin-left: 24px;
}
</style>
